//
//  UIColor+Category.m
//  Teleport
//
//  Created by RLY on 2020/5/14.
//  Copyright © 2020 xxt. All rights reserved.
//

#import "UIColor+Category.h"

@implementation UIColor (Category)


+ (nonnull UIColor *)tj_randomColor {
    u_int8_t red = arc4random_uniform(256);
    u_int8_t green = arc4random_uniform(256);
    u_int8_t blue = arc4random_uniform(256);
    
    return [UIColor tj_colorWithRed:red green:green blue:blue];
}

+ (nonnull UIColor *)tj_colorWithRed:(u_int8_t)red green:(u_int8_t)green blue:(u_int8_t)blue {
    return [UIColor colorWithRed:red / 255.0 green:green / 255.0 blue:blue / 255.0 alpha:1.0];
}


+ (UIColor *)tj_colorWithHexString:(NSString *)hexColor {
    NSString * cString = [[hexColor stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];
    // String should be 6 or 8 characters
    if ([cString length] < 6) return [UIColor blackColor];
    // strip 0X if it appears
    if ([cString hasPrefix:@"0X"]) cString = [cString substringFromIndex:2];
    if ([cString hasPrefix:@"#"]) cString = [cString substringFromIndex:1];
    if ([cString length] != 6) return [UIColor blackColor];
    // Separate into r, g, b substrings
    NSRange range;
    range.location = 0;
    range.length = 2;
    NSString * rString = [cString substringWithRange:range];
    range.location = 2;
    NSString * gString = [cString substringWithRange:range];
    range.location = 4;
    NSString * bString = [cString substringWithRange:range];
    // Scan values
    unsigned int r, g, b;
    [[NSScanner scannerWithString:rString] scanHexInt:&r];
    [[NSScanner scannerWithString:gString] scanHexInt:&g];
    [[NSScanner scannerWithString:bString] scanHexInt:&b];
    
    return [UIColor colorWithRed:((float)r / 255.0f)
                           green:((float)g / 255.0f)
                            blue:((float)b / 255.0f)
                           alpha:1];
}

+ (UIColor *)tj_colorWithHex:(int)hex {
    return [UIColor colorWithRed:((hex & 0xFF0000) >> 16) / 255.0 green:((hex & 0x00FF00) >> 8) / 255.0 blue:(hex & 0x0000FF) / 255.0 alpha:1.0];
}

- (id)mutableCopy {
    CGFloat red, green, blue, alpha;
    BOOL success = [self getRed:&red green:&green blue:&blue alpha:&alpha];
    if (success) {
        return [[UIColor alloc] initWithRed:red green:green blue:blue alpha:alpha];
    } else {
        return nil;
    }
}

- (NSString *)hexString {
    CGFloat red, green, blue;
    if ([self getRed:&red green:&green blue:&blue alpha:nil]) {
        NSString *hex = [NSString stringWithFormat:@"#%02lX%02lX%02lX", lroundf(red * 255), lroundf(green * 255), lroundf(blue * 255)];
        return hex;
    }
    return @"#000000"; // 返回黑色的16进制代码作为默认值
}



@end
